#!/usr/bin/python3.5
# -*- coding: utf-8 -*-

from netmiko import ConnectHandler
from ftp_client import main
import os
import time
import re

def Cisco(ip):
	#cisco swith_config export function
	cisco_881 = {
	'device_type': 'cisco_ios',
	'ip': ip,
	'username': 'cisco',
	'password': 'cisco',
	'port': '22',
#	'secret': 'cisco',
	'verbose': False,
	}
	print (u'正在连接Devices：{0}\n'.format(ip))
	net_connect = ConnectHandler(**cisco_881)
	net_connect.enable()
	# commands = [
	# 'show arp',
	# ]
#获取本地时间并且格式化输出
	timestr = time.strftime('%Y-%m-%d', time.localtime(time.time()))
	for cmds in open('commands','r'):
		#replace把文件内容结束符替换为空否则答应出来是带有换行符
		cmd = cmds.replace('\n','')
		#定义文件名字eg:1_1_1_1_show_arp_3_3.txt
		filename = (u'{0}_{1}_{2}.txt'.format(ip,cmd.replace(' ','_'), timestr))
		#创建文件文件为刚才自定义的filename
		save = open(filename, 'w')
		print (u'正在执行命令：' + cmd)
		#将for循环取出来的命令一条一条的执行，将结果赋值给result变量
		result = net_connect.send_command(cmd)
		#把命令结果存储在文件中
		save.write(result)
		print(u'命令执行完毕，结果保存于当前目录{0}中!\n'.format(filename))
	net_connect.disconnect()

if __name__ == '__main__':
	# ips = [
	# '192.168.31.232',
	# ]
	for ips in open('ips','r'):
		ip = ips.replace('\n','')
		Cisco(ip)
	time.sleep(1)
	print (u'=====上传文件至目标服务器=====')
	main()
	print (u'\n文件上传成功!')

'''
	#上传文件至目标服务器
	rsync = 'rsync -avz --password-file=rsync.passwd *.txt root@192.168.31.231::upload'
	#列出目标服务器列表
	#'rsync --list-only -v root@192.168.31.231::upload'
	if os.system(rsync) == 0:
		print (u'文件上传成功！')
	else:
		print (u'文件上传失败！')
'''	